<template>
  <view v-show="pageLoaded" class="container">
    <u-navbar title="商城" placeholder :bg-color="navbarBgColor">
      <template v-slot:left></template>
    </u-navbar>
    <view
      class="container-bg"
      :style="{
        top: 0,
      }"
    ></view>
    <view class="search">
      <search
        height="78rpx"
        bg="linear-gradient(180deg, rgba(255, 237, 226, 0.74) 0%, rgba(255, 255, 255, 0.58) 100%)"
        bg-color="transparent"
        :customStyle="{
          'border-radius': '16rpx',
        }"
        placeholderColor="rgba(0, 0, 0, 0.3)"
        color="rgba(0, 0, 0, 0.7)"
        placeholder="搜索文创商品"
        :showAction="false"
        v-model="keyword"
        @search="search"
      >
        <template v-slot:clickIcon>
          <view class="icon-search" @click="search"></view>
        </template>
      </search>
    </view>
    <view
      class="sticky"
      :style="{
        top: $u.addUnit($u.sys().statusBarHeight + 42, 'px'),
        'background-color': stickyBgColor,
      }"
    >
      <view class="tabs-line">
        <tabs
          :list="tabs"
          :current="tabIndex"
          lineWidth="0"
          :gradient="true"
          :item-style="{
            height: '84rpx',
            padding: '0 20rpx 14rpx',
            'align-items': 'flex-end',
          }"
          :active-style="{
            'font-size': '40rpx',
            'font-weight': 600,
            color: 'rgba(0, 0, 0, 0.9)',
            'line-height': '56rpx',
          }"
          :inactive-style="{
            'font-size': '32rpx',
            'font-weight': 600,
            color: 'rgba(0, 0, 0, 0.9)',
            'line-height': '48rpx',
          }"
          @change="getList"
        ></tabs>
      </view>
      <view class="tabs-sub">
        <tabs
          :list="tabs2"
          :current="tab2Index"
          lineWidth="0"
          :item-style="{
            padding: '24rpx 8rpx 8rpx',
          }"
          :active-style="{
            display: 'block',
            padding: '12rpx 20rpx 10rpx',
            border: '1px solid #ff5000',
            background: '#ff5000',
            'box-shadow': '0rpx 10rpx 24rpx -10rpx rgba(255, 113, 58, 0.25)',
            'border-radius': '12rpx',
            'font-size': '24rpx',
            'font-weight': 600,
            color: '#fff201',
            'line-height': '34rpx',
          }"
          :inactive-style="{
            display: 'block',
            padding: '12rpx 20rpx 10rpx',
            border: '1px solid rgba(0, 0, 0, 0.1)',
            background: '#ffffff',
            'border-radius': '12rpx',
            'font-size': '24rpx',
            'font-weight': 600,
            color: 'rgba(0, 0, 0, 0.9)',
            'line-height': '34rpx',
          }"
          @change="getList2"
        ></tabs>
      </view>
    </view>
    <view class="goods">
      <view
        class="goods-item"
        v-for="item of list"
        :key="item.id"
        @click="toURL('/page_mall/detail/detail', { id: item.id })"
      >
        <u-image
          :src="img_api + item.imgPath"
          width="100%"
          height="332rpx"
        ></u-image>
        <view class="goods-content">
          <view class="goods-name u-line-2">{{ item.name }}</view>
          <view class="goods-price">{{ item.toShowPrice }}</view>
        </view>
      </view>
    </view>
    <no-data v-if="list.length === 0"></no-data>
    <view
      class="shoppingCart"
      @click="toURL('/page_mall/cart/index', {}, { isAuth: true })"
    >
      <u-image
        src="https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-cart.png"
        mode="aspectFill"
        width="48rpx"
        height="48rpx"
      ></u-image>
      <text class="number" v-if="mobileCartNum !== 0">{{ mobileCartNum }}</text>
    </view>
  </view>
</template>

<script>
import {
  getCartCount,
  getShopCategoryList,
  getShopGoodsList,
} from "@/config/api";
import search from "@/components/search/search.vue";
import noData from "@/components/noData.vue";
import tabs from "@/components/tabs/tabs.vue";

export default {
  components: {
    search,
    noData,
    tabs,
  },
  data() {
    return {
      pageLoaded: false,
      loading: 2, // 0:不再加载; 1:加载中; 2:加载完成;
      pageNum: 1,
      pageSize: 10,
      keyword: "",
      tabs: [],
      tabIndex: -1,
      tabs2: [],
      tab2Index: -1,
      list: [],
      scrollTop: 0,
      mobileCartNum: 0,
    };
  },
  computed: {
    navbarBgColor() {
      return this.scrollTop > 0 ? "#ffffff" : "transparent";
    },
    stickyBgColor() {
      return this.scrollTop > uni.$u.getPx("100rpx")
        ? "#ffffff"
        : "transparent";
    },
  },
  watch: {},
  onLoad() {
    Promise.all([this.loadTypes({ level: 1 })])
      .then(([tabs]) => {
        this.tabs = tabs.map((item) => {
          return {
            id: item.id,
            name: item.name,
          };
        });
        return this.getList({ index: 0 });
      })
      .then(() => {
        this.pageLoaded = true;
      });
  },
  onReady() {},
  onShow() {
    this.loadCartCount();
  },
  onReachBottom() {
    this.getListFromNext();
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  methods: {
    search() {
      this.getListFromSearchType();
    },
    typeId() {
      return this.tabs2[this.tab2Index]?.id || this.tabs[this.tabIndex].id;
    },
    getList({ index }) {
      this.tabIndex = index;
      this.tab2Index = -1;
      return Promise.all([
        this.loadTypes({ parentId: this.tabs[index].id }).then((tabs) => {
          this.tabs2 = tabs.map((item) => {
            return {
              id: item.id,
              name: item.name,
            };
          });
        }),
        this.getListFromSearchType(),
      ]);
    },
    getList2({ index }) {
      this.tab2Index = index;
      return this.getListFromSearchType();
    },
    getListFromSearchType() {
      this.pageNum = 1;
      this.loading = 2;
      return this.loadList(this.typeId()).then(() => {
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 0,
        });
      });
    },
    getListFromNext() {
      if (this.loading === 0 || this.loading === 1) return;
      this.pageNum++;
      this.loadList(this.typeId());
    },
    loadCartCount() {
      if (this.token) {
        return getCartCount().then(({ code, data }) => {
          if (code !== 200) {
            data = 0;
          }
          this.mobileCartNum = Number(data);
        });
      } else {
        return Promise.resolve();
      }
    },
    loadTypes(params) {
      return getShopCategoryList(params).then(({ code, data: tabs }) => {
        if (code !== 200) {
          tabs = [];
        }
        return tabs;
      });
    },
    loadList(typeId) {
      if (this.loading === 1) {
        return Promise.reject({
          msg: "loading...",
        });
      }
      this.loading = 1;
      return getShopGoodsList({
        ...(this.keyword ? { name: this.keyword } : {}),
        categoryId: typeId,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then(({ code, rows: lists, total }) => {
        if (typeId !== this.typeId()) {
          return;
        }

        if (code !== 200) {
          lists = [];
          total = 0;
        }

        for (const item of lists) {
          item.toShowPrice = Number(`${item.price}e-2`).toFixed(2);
        }

        if (this.pageNum === 1) {
          this.list = [].concat(lists);
        } else {
          this.list = this.list.concat(lists);
        }

        if (lists.length < this.pageSize || total === this.list.length) {
          this.loading = 0;
        } else {
          this.loading = 2;
        }
      });
    },
  },
};
</script>

<style>
page {
  background: #f9f6f5;
}
</style>

<style lang="scss" scoped>
.container {
  position: relative;

  .sticky {
    position: sticky;
    z-index: 1;
  }

  .container-bg {
    position: absolute;
    left: 0;
    width: 750rpx;
    height: 694rpx;
    background: linear-gradient(
          180deg,
          rgba(255, 242, 237, 0.9) 0%,
          #f9f6f5 100%
        )
        left top no-repeat,
      url("https://ltjt.sjzballsportpark.com/statics/tyc/static/mall-topBg.jpg") center
        no-repeat;
    background-size: 750rpx 694rpx, cover;
  }

  .search::v-deep {
    height: 100rpx;
    display: flex;
    align-items: center;
    padding: 0 32rpx;
    position: relative;
    z-index: 1;

    .icon-search {
      width: 32rpx;
      height: 32rpx;
      background: url("https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-search.png")
        center no-repeat;
      background-size: contain;
    }

    .u-search__content {
      padding: 0 16rpx;
      border: 3rpx solid rgba(255, 255, 255, 0.5);
      box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(187, 101, 31, 0.1);
    }

    .u-search__content__input {
      margin: 0 16rpx;
    }
  }

  .tabs-line::v-deep {
    .u-tabs__wrapper__nav {
      border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
    }

    .u-tabs__wrapper__nav__item {
      &:first-of-type {
        padding-left: 32rpx !important;
      }

      &:nth-last-of-type(2) {
        padding-right: 32rpx !important;
      }
    }
  }

  .tabs-sub::v-deep {
    .u-tabs__wrapper__nav__item {
      &:first-of-type {
        padding-left: 32rpx !important;
      }

      &:nth-last-of-type(2) {
        padding-right: 32rpx !important;
      }
    }
  }

  .goods {
    position: relative;
    display: flex;
    flex-flow: row wrap;
    padding: 32rpx 32rpx 8rpx 10rpx;

    .goods-item {
      flex: none;
      width: calc(50% - 22rpx);
      margin-left: 22rpx;
      border-radius: 16rpx;
      margin-bottom: 22rpx;
      overflow: hidden;

      .goods-content {
        padding: 16rpx 16rpx 20rpx;
        background: #ffffff;
      }

      .goods-name {
        height: 80rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.7);
        line-height: 40rpx;
      }

      .goods-price {
        background: url("https://ltjt.sjzballsportpark.com/statics/tyc/static/icon-RMB.png")
          left center no-repeat;
        background-size: 32rpx 32rpx;
        padding-left: 32rpx;
        margin-top: 24rpx;
        font-size: 40rpx;
        font-family: D-DIN-Bold;
        font-weight: 700;
        color: #ff5000;
        line-height: 44rpx;
      }
    }
  }

  .shoppingCart {
    position: fixed;
    bottom: 44rpx;
    right: 32rpx;
    width: 96rpx;
    height: 96rpx;
    border-radius: 48rpx;
    background: #ffffff;
    border: 2rpx solid rgba(0, 0, 0, 0.1);
    z-index: 2;
    display: flex;
    justify-content: center;
    align-items: center;

    .number {
      width: 32rpx;
      height: 32rpx;
      background: #ffffff;
      border-radius: 16rpx;
      position: absolute;
      top: 4rpx;
      right: 4rpx;
      font-size: 24rpx;
      font-family: D-DIN-Bold;
      font-weight: 700;
      color: #ff7614;
      line-height: 32rpx;
      text-align: center;
    }
  }
}
</style>
